<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\service\user;

use app\common\model\User as UserModel;
use think\facade\Db;

class StatisticsService
{
    /**
     * 获取会员统计概览数据
     */
    public function getOverview()
    {
        return [
            'total_users'     => $this->getTotalUsers(),
            'today_users'     => $this->getTodayUsers(),
            'yesterday_users' => $this->getYesterdayUsers(),
            'month_users'     => $this->getMonthUsers(),
            'active_users'    => $this->getActiveUsers(),
            'paid_users'      => $this->getPaidUsers()
        ];
    }

    /**
     * 获取总会员数
     */
    public function getTotalUsers()
    {
        return UserModel::count();
    }

    /**
     * 获取今日新增会员数
     */
    public function getTodayUsers()
    {
        return UserModel::whereDay('create_time')->count();
    }

    /**
     * 获取昨日新增会员数
     */
    public function getYesterdayUsers()
    {
        return UserModel::whereDay('create_time', 'yesterday')->count();
    }

    /**
     * 获取本月新增会员数
     */
    public function getMonthUsers()
    {
        return UserModel::whereMonth('create_time')->count();
    }

    /**
     * 获取活跃会员数（30天内有登录记录）
     */
    public function getActiveUsers()
    {
        return UserModel::where('lastlogintime', '>', strtotime('-30 days'))->count();
    }

    /**
     * 获取付费会员数（有成功支付订单的会员）
     */
    public function getPaidUsers()
    {
        return Db::name('user_order')
            ->alias('uo')
            ->join('goods_order go', 'uo.order_id = go.id')
            ->where('go.status', 1)
            ->group('uo.user_id')
            ->count('uo.user_id');
    }

    /**
     * 获取会员增长趋势数据
     */
    public function getGrowthTrend($days = 30)
    {
        if ($days > 90) {
            $days = 90; // 最多查询90天数据
        }

        $result = [];

        for ($i = $days - 1; $i >= 0; $i--) {
            $date      = date('Y-m-d', strtotime("-$i days"));
            $startTime = strtotime($date);
            $endTime   = strtotime($date . ' 23:59:59');

            // 当天注册用户数
            $userCount = UserModel::where('create_time', '>=', $startTime)
                ->where('create_time', '<=', $endTime)
                ->count();

            $result[] = [
                'date'  => $date,
                'count' => $userCount
            ];
        }

        return $result;
    }

    /**
     * 获取会员消费排行数据
     */
    public function getConsumptionRanking($limit = 10)
    {
        // 查询消费金额排行
        $ranking = Db::name('user_order')
            ->alias('uo')
            ->join('goods_order go', 'uo.order_id = go.id')
            ->field('uo.user_id, sum(go.total_price) as total_amount, count(go.id) as order_count')
            ->where('go.status', 1)
            ->group('uo.user_id')
            ->order('total_amount desc')
            ->limit($limit)
            ->select()
            ->toArray();

        // 补充用户信息
        foreach ($ranking as &$item) {
            $user = UserModel::field('id, nickname, email, avatar')->find($item['user_id']);
            if ($user) {
                $item['user_info'] = $user;
            } else {
                $item['user_info'] = [
                    'id'       => $item['user_id'],
                    'nickname' => '未知用户',
                    'email'    => '',
                    'avatar'   => ''
                ];
            }
        }

        return $ranking;
    }

    /**
     * 获取会员活跃度分析数据
     */
    public function getActivityAnalysis()
    {
        return [
            'today'     => UserModel::whereDay('lastlogintime')->count(), // 今日登录
            'yesterday' => UserModel::where('lastlogintime', '>=', strtotime('yesterday'))
                ->where('lastlogintime', '<', strtotime('today'))
                ->count(), // 昨日登录
            'week'      => UserModel::where('lastlogintime', '>=', strtotime('-7 days'))
                ->where('lastlogintime', '<', strtotime('yesterday'))
                ->count(), // 一周内登录
            'month'     => UserModel::where('lastlogintime', '>=', strtotime('-30 days'))
                ->where('lastlogintime', '<', strtotime('-7 days'))
                ->count(), // 一月内登录
            'older'     => UserModel::where(function ($query) {
                $query->where('lastlogintime', '<', strtotime('-30 days'))
                    ->whereOr('lastlogintime', 'null');
            })->count() // 更早登录或从未登录
        ];
    }
}